package com.yilin.platform.controller.user;

import com.yilin.platform.base_core.application.BaseController;
import com.yilin.platform.base_core.application.ReturnData;
import com.yilin.platform.base_core.commons.utils.ParamUtil;
import com.yilin.platform.base_core.commons.utils.StringUtil;
import com.yilin.platform.base_core.commons.annotation.SkipLoginVerify;
import com.yilin.platform.base_core.commons.annotation.UserTarget;
import com.yilin.platform.base_core.tools.SMSUtil;
import com.yilin.platform.entity.enums.user.OrganType;
import com.yilin.platform.entity.enums.user.RoleType;
import com.yilin.platform.entity.enums.user.UserType;
import com.yilin.platform.entity.system.Jurisdiction;
import com.yilin.platform.entity.user.Account;
import com.yilin.platform.entity.user.Organize;
import com.yilin.platform.service.impl.system.JurisdictionService;
import com.yilin.platform.service.impl.user.AccountService;
import com.yilin.platform.service.impl.user.AuthorityService;
import com.yilin.platform.service.impl.user.OrganizeService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/register")
public class RegisterController extends BaseController {


    @Resource
    private OrganizeService organizeService;
    @Resource
    private AccountService accountService;
    @Resource
    private JurisdictionService jurisdictionService;
    @Resource
    private AuthorityService authorityService;
    /**
     * 手机号开放注册渠道  司机个体注册  个体 新
     * 验证码注册
     */
    @PostMapping("phoneRegister")
    @SkipLoginVerify //开放注册/无需上游登录
    public ReturnData phoneRegister(Account account) {
        if (StringUtil.isEmpty(account.getPhone())) {
            return jsonView(false, "注册手机号不能为空！");
        }
//        if (StringUtil.isEmpty(account.getSuperiorPlatId())) {
//            return jsonView(false, "请绑定你的公司！");
//        }
        if (StringUtil.isEmpty(account.getVerCode())) {
            return jsonView(false, "请输入收到的6位手机验证码！");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() < 8) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        Account accountPhone=accountService.getAccountPhone(account.getPhone());
        if(accountPhone!=null)return jsonView(false, "该手机号已存在，请直接登录");
        // ### 检查手机验证码
        Map<String, Object> verifyCode = SMSUtil.verifyCode(account.getPhone(), account.getVerCode(), SMSUtil.MsgType.organizeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        Organize organize = new Organize();
        organize.setUserType(UserType.truckerUser);
        organize.setOrganType(OrganType.individual);
        if(StringUtil.isNotEmpty(account.getSuperiorPlatId())){
            organize.setSuperiorPlatOrganizeId(account.getSuperiorPlatId());
            organize.setSuperiorPlatOrganizeName(account.getSuperiorPlatName());
        }else{
            organize.setOrganType(OrganType.free);
        }
        //###初始化账户信息
        account.setUsername(account.getPhone());
        account.setUserType(organize.getUserType());
        account.setOrganType(organize.getOrganType());
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.applets);
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "注册成功");
    }

    /**
     * 授权组织 个体注册 新
     * 验证码注册
     */
    @PostMapping("authorizedRegister")
    @UserTarget(UserType.platformUser)
    public ReturnData authorizedRegister(Organize organize, Account account) {
        if(getLoginUser().getUserType()!=UserType.platformUser&&getLoginUser().getRoleType()!=RoleType.manager){
            return jsonView(false,"您没有权限添加");
        }
        ParamUtil.isNull(organize.getOrganType(), "授权主体未选择");
        ParamUtil.isNull(organize.getOrganizeName(), "请输入授权组织名称");
        ParamUtil.isNull(organize.getAuthorizedState(), "请选择授权状态");
        ParamUtil.isNull(organize.getTruckNumber(), "请输入授权数量");
        ParamUtil.isNull(account.getUsername(), "请输入授权账号");
        ParamUtil.isNull(account.getPhone(), "请输入手机号");
        ParamUtil.isNull(account.getVerCode(), "请输入验证码");
        ParamUtil.isNull(account.getPassword(), "请设置至少8位登录密码");
        if (account.getPassword().length() < 8) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        // ### 检查手机验证码
        Map<String, Object> verifyCode = SMSUtil.verifyCode(account.getPhone(), account.getVerCode(), SMSUtil.MsgType.organizeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        organize.setUserType(UserType.truckerUser);
        organize.setAuthorized(true);
        account.setUserType(organize.getUserType());
        account.setOrganType(organize.getOrganType());
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.applets);
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "注册成功");
    }

    /**
     * 管理员添加
     * 员工注册通道
     */
    @PostMapping("employeeRegister")
    @Transactional
    public ReturnData employeeRegister(Account employee, String[] jurisdictionIds) {
        Account loginUser = getLoginUser();
        if (loginUser.getRoleType() != RoleType.manager) {
            return jsonView(false, "您无权添加员工");
        }
        if (StringUtil.isEmpty(employee.getRoleName())) {
            return jsonView(false, "请为员工角色名称账号！");
        }
        if (StringUtil.isEmpty(employee.getPhone())) {
            return jsonView(false, "请填写员工手机号！");
        }
        if (StringUtil.isEmpty(employee.getName())) {
            return jsonView(false, "请填写员工姓名！");
        }
        if (StringUtil.isEmpty(employee.getPassword())) {
            return jsonView(false, "请设置员工密码！");
        }
        if (StringUtil.isEmpty(employee.getVerCode())) {
            return jsonView(false, "请向员工索要验证码！");
        }
        Map<String, Object> verifyCode = SMSUtil.verifyCode(employee.getPhone(), employee.getVerCode(), SMSUtil.MsgType.employeeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        employee.setRoleType(RoleType.employee);
        employee.setUsername(employee.getPhone());
        Organize organize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        employee = accountService.employeeRegister(organize, employee, jurisdictionIds);
        return jsonView(true, "员工注册成功");
    }

    /**
     * 管理员添加
     * 员工注册通道
     */
    @PostMapping("updateEmployeeRegister")
    @Transactional
    public ReturnData updateEmployeeRegister(String accountId, String roleName, String[] jurisdictionIds) {

        ParamUtil.isNull(accountId, "请传入用户信息");
        ParamUtil.isNull(roleName, "请传入角色名称");
        Account account = accountService.getAccountById(accountId);
        ParamUtil.isNull(account, "用户信息获取失败");
        account.setRoleName(roleName);
        if(jurisdictionIds!=null){
            List<Jurisdiction> jurisdictionList=jurisdictionService.getJurisdictionListByIds(jurisdictionIds);
            if(jurisdictionList!=null&& !jurisdictionList.isEmpty()){
                authorityService.saveAuthority(account,jurisdictionList);
            }
        }
        accountService.saveOrUpdate(account);
        return jsonView(true, "员工注册成功");
    }

}